import tkinter as tk
from tkinter import messagebox
from time import sleep, time, localtime
import pywinauto.keyboard
import win32gui, win32ui, win32con, win32api
import pywinauto
import random
from threading import Timer

class BuyItemsController:
  def __init__(self, tk_root) -> None:
    self.tk_root = tk_root
    self.start_flag = False
    self.next_run_time = 0
    self.timer = None
    self.wow_handle = None
    self.build_ui()

  def build_ui(self):
    tk.Button(self.tk_root, text="启动购买", command=self.start).place(x=10, y=10, width=80, height=30)
    tk.Button(self.tk_root, text="停止购买", command=self.stop).place(x=100, y=10, width=80, height=30)

  def focusWow(self, open_bag):
    try:
      self.wow_handle = pywinauto.findwindows.find_windows(best_match='魔兽世界')[0]
    except:
      messagebox.showerror("错误", "未找到WOW句柄")
    if self.wow_handle is None:
      return
    # handle = pywinauto.findwindows66666.find_windows(best_match='vs.txt')[0]
    app = pywinauto.application.Application().connect(handle=self.wow_handle)
    window = app.window()
    # 打开背包
    if open_bag:
        window.type_keys("{VK_F10}")
  
  def start(self):
    self.focusWow(True)
    if self.wow_handle is None:
      return
    self.next_run_time = int(time()) + 20
    # 按键对照表
    # https://www.cnblogs.com/chenxi188/p/11642006.html
    # 36 -> 3 * 16 + 6 = 54
    self.run_script()
          

  def run_script(self):
    if self.timer:
      self.timer.cancel()
    # print(time())
    if localtime(time()).tm_min % 2 == 0:
      self.focusWow(False)
    win32api.keybd_event(0x36, 0, 0, 0)
    win32api.keybd_event(0x36, 0, win32con.KEYEVENTF_KEYUP, 0)
    self.run_user()
    self.timer = Timer(random.random(), self.run_script)
    self.timer.start()

  def run_user(self):
    if int(time()) > self.next_run_time:
      print("run")
      win32api.keybd_event(0x57, 0, 0, 0)
      sleep(0.01)
      win32api.keybd_event(0x57, 0, win32con.KEYEVENTF_KEYUP, 0)
      self.next_run_time = int(time()) + random.randint(20, 50)

  def stop(self):
    if self.timer:
      self.timer.cancel()